package com.ys.controller.api.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ys.config.MenuId;
import com.ys.entity.base.TsBatchImportLog;
import com.ys.entity.sys.YsCol;
import com.ys.enume.base.TsBatchImportLogEnum;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.UploadService;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/api/inter/tsBatchImportLog")
public class ApiInterTsBatchImportLogController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTsBatchImportLogController.class);
	
	@Autowired
	private CommonApiService<TsBatchImportLog> commonApiService;

	//菜单id
	private Long menuIdByTosProductBasis = MenuId.TS_BatchImportLog_ByTosProductBasis;
	private Long menuIdByTosProductActive = MenuId.TS_BatchImportLog_ByTosProductActive;

	private Long menuIdByTbProductBasis = MenuId.TS_BatchImportLog_TpProductBasis;
	private Long menuIdByTbProductBasisSub = MenuId.TS_BatchImportLog_TpProductBasisSub;

	//权限字符
	private final String PERMISSIONS_VIEW = "tsBatchImportLog:view";

	//@Autowired
	//private TbCountryService tbCountryService;



	//导入详情查询，从导入信息跳转过来
	//@RequiresPermissions(PERMISSIONS_VIEW)
	@RequestMapping("/searchFromInfo")
    @ResponseBody
	public LayuiTableVoJA searchFromInfo(@ModelAttribute TsBatchImportLog cond,String conditions){

		cond.addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS infoCreateTime");//导入时间
		cond.addField("A.ImportState AS _ys_importState");
		cond.setUserId(ShiroUtils.getUserId());

		//导入状态
		String importState = ConditionUtil.getConditionValue(conditions, "_ys_importState");//导入状态
		if (importState != null){
			if(importState.equals("-1")){
				cond.where("A.ImportState IN ("+TsBatchImportLogEnum.ImportState.FAIL.value+","+TsBatchImportLogEnum.ImportState.NO.value+")");
			}else {
				cond.setImportState(Integer.parseInt(importState));
			}
		}

		//排序
		cond.setOrderby("A.Id DESC");
		LayuiTableVoJA setList = commonApiService.searchLay(cond);
		//获取
		JSONArray tableVoJAData = setList.getData();

		//转换
		List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
		List<Map<String, Object>> resListNew = new ArrayList();
		resList.forEach(item-> resListNew.add(item));
		List<Map<String, Object>> resultList = new ArrayList();
		//处理数据
		if(resListNew.size()>0) resultList = setList(resListNew,"importInfo");
		JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resultList));
		setList.setData(jsonArray);

		return setList;
	}


	//处理返回的数据，将JSON类型转换成具体返回字段
	public List<Map<String, Object>> setList(List<Map<String, Object>> resDate,String strCode) {
		List<Map<String, Object>> newList = new ArrayList<>();
		for(Map<String, Object> infoMap:resDate){
			if(infoMap.get(strCode)!=null){
				String importInfo = infoMap.get(strCode).toString();
				JSONObject info = JSONObject.parseObject(importInfo);
				for (String key : info.keySet()) {
					infoMap.put(key, info.get(key));
				}
			}
			newList.add(infoMap);
		}
		return newList;
	}

	public R doExportError(long menuId,String sheetName, TsBatchImportLog cond)throws Exception{
		cond.setPage(0).setSize(999999);
		cond.addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS infoCreateTime");//导入时间
		cond.setUserId(ShiroUtils.getUserId());
		cond.setImportState(TsBatchImportLogEnum.ImportState.FAIL.value);

		//获取菜单字段数据
		List<YsCol> listField = new YsCol()
				.setMenuId(menuId)
				.setFrontShow(1)
				.where("A.Code NOT IN ('_ys_importState','infoCreateTime','failReason')")
				.setOrderby("A.SortNo asc")
				.queryList();
		//获取数据
		List<Map<String, Object>> listData = cond.queryMap();
		listData = setList(listData,"importInfo");

		//处理数据
		ExportExcelUtils<TsBatchImportLog> util = new ExportExcelUtils<>(new TsBatchImportLog());
		String toFilePath = util.exportExcel(listData, listField, sheetName);
		UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
		return R.ok(dto.getUrl());
	}


	/**
     * 导出错误信息 - HW商品库
     */
    @RequestMapping("/exportErrorByTosProductBasis")
    @ResponseBody
    public R exportErrorByTosProductBasis(@ModelAttribute TsBatchImportLog cond, String conditions){
        try {
			return doExportError(menuIdByTosProductBasis,"HW商品库导入错误信息",cond);
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }



	/**
	 * 导出错误信息 - HW商品listing库
	 */
	@RequestMapping("/exportErrorByTosProductActive")
	@ResponseBody
	public R exportErrorByTosProductActive(@ModelAttribute TsBatchImportLog cond, String conditions){
		try {
			return doExportError(menuIdByTosProductActive,"HW商品listing库导入错误信息",cond);
		}catch (Exception e){
			logger.error("导出出错：",e.getMessage(),e);
			return R.error("导出失败，请稍后重试！");
		}
	}








	//导入详情查询，从导入信息跳转过来
	//@RequiresPermissions(PERMISSIONS_VIEW)
	@RequestMapping("/searchFromInfoByTpProductBasis")
	@ResponseBody
	public LayuiTableVoJA searchFromInfoByTpProductBasis(@ModelAttribute TsBatchImportLog cond,String conditions){

		cond.addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS infoCreateTime");//导入时间
		cond.addField("A.ImportState AS _ys_importState");
		cond.setUserId(ShiroUtils.getUserId());

		//查询条件
		String pid = ConditionUtil.getConditionValue(conditions, "pid");//导入批次id

		cond.addLeftJoin("TS_BatchImportLog B ON B.LevIdOne = A.Id AND B.Pid = "+pid)
				.addField("B.ImportInfo AS subImportInfo");

		cond.where("A.InfoType = "+TsBatchImportLogEnum.InfoType.TP_ProductBasis.value + " OR (A.InfoType = "+TsBatchImportLogEnum.InfoType.TP_ProductBasisComponent.value+" AND A.LevIdOne IS NULL)"  );


		//导入状态
		String importState = ConditionUtil.getConditionValue(conditions, "_ys_importState");//导入状态
		if (importState != null){
			if(importState.equals("-1")){
				cond.where("A.ImportState IN ("+TsBatchImportLogEnum.ImportState.FAIL.value+","+TsBatchImportLogEnum.ImportState.NO.value+")");
			}else {
				cond.setImportState(Integer.parseInt(importState));
			}
		}

		//排序
		cond.setOrderby("A.Id DESC");
		LayuiTableVoJA setList = commonApiService.searchLay(cond);
		//获取
		JSONArray tableVoJAData = setList.getData();

		//转换
		List<Map> resList = JSONArray.parseArray(JSON.toJSONString(tableVoJAData),Map.class);
		List<Map<String, Object>> resListNew = new ArrayList();
		resList.forEach(item-> resListNew.add(item));
		List<Map<String, Object>> resultList = new ArrayList();
		//处理数据
		if(resListNew.size()>0) {
			resultList = setList(resListNew,"importInfo");
			resultList = setList(resultList,"subImportInfo");
		}
		JSONArray jsonArray = JSONArray.parseArray(JSON.toJSONString(resultList));
		setList.setData(jsonArray);

		return setList;
	}



	/**
	 * 导出错误信息 - 商品库批量导入 - 母表信息
	 */
	@RequestMapping("/exportMainErrorByTbProductBasis")
	@ResponseBody
	public R exportMainErrorByTbProductBasis(@ModelAttribute TsBatchImportLog cond, String conditions){
		try {
			return doExportErrorByTbProductBasis(menuIdByTbProductBasis,"商品库批量导入-商品母表错误信息",cond);
		}catch (Exception e){
			logger.error("导出出错：",e.getMessage(),e);
			return R.error("导出失败，请稍后重试！");
		}
	}




	/**
	 * 导出错误信息 - 商品库批量导入 - 子表信息
	 */
	@RequestMapping("/exportSubErrorByTbProductBasis")
	@ResponseBody
	public R exportSubErrorByTbProductBasis(@ModelAttribute TsBatchImportLog cond, String conditions){
		try {
			return doExportErrorByTbProductBasis(menuIdByTbProductBasisSub,"商品库批量导入-商品子表错误信息",cond);
		}catch (Exception e){
			logger.error("导出出错：",e.getMessage(),e);
			return R.error("导出失败，请稍后重试！");
		}
	}


	public R doExportErrorByTbProductBasis(long menuId,String sheetName, TsBatchImportLog cond)throws Exception{
		cond.setPage(0).setSize(999999);
		cond.addField("FORMAT(A.CreateTime, 'yyyy-MM-dd HH:mm:ss') AS infoCreateTime");//导入时间
		cond.setUserId(ShiroUtils.getUserId());
		cond.setImportState(TsBatchImportLogEnum.ImportState.FAIL.value);

		//获取菜单字段数据
		List<YsCol> listField = new YsCol()
				.setMenuId(menuId)
				.setFrontShow(1)
				.where("A.Code NOT IN ('_ys_importState','infoCreateTime','failReason')")
				.setOrderby("A.SortNo asc")
				.queryList();
		//获取数据
		List<Map<String, Object>> listData = cond.queryMap();

		if(listData.size()>0) {
			listData = setList(listData,"importInfo");
			listData = setList(listData,"subImportInfo");
		}

		//处理数据
		ExportExcelUtils<TsBatchImportLog> util = new ExportExcelUtils<>(new TsBatchImportLog());
		String toFilePath = util.exportExcel(listData, listField, sheetName);
		UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
		return R.ok(dto.getUrl());
	}




}
